/**
 * create by young (young2f@outlook.com) on 2020/9/12
 */

'use strict';
import React from 'react';
import {connect} from 'dva/index';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Drawer,
  Dropdown,
  Form,
  Input,
  Menu,
  Popconfirm,
  Row,
  Select,
  Statistic,
  Table
} from 'antd';

import styles from '../index.less';
import ModalCreateOrEditProcureOrder from './modal/ModalCreateOrEditProcureOrder';
import ViewTitle from '../../components/ViewTitle';
import FormBase from '../../components/Base/FormBase';
import notify from "../../components/NotificationExtra";
import {FormField, ModalView, SearchForm} from 'antd-extra';
import moment from 'moment';
import 'moment/locale/zh-cn';
import ModalProcureOrderDetail from "./modal/ModalProcureOrderDetail";
import {exportExcel} from '../../utils/excelUtils';
import Icon from "antd/es/icon";

moment.locale('zh-cn');
const {RangePicker} = DatePicker;
const _ = require('lodash');
const {Option} = Select;
const table = 'ProcureOrder';
const title = '采购单';

@Form.create()
@connect(({
            user,
            global,
            dict,
            vendor,
            procure
          }) => ({...user, ...global, ...procure, ...dict, ...vendor}))
export default class Index extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const {dispatch} = this.props;
    const payload = this.props.form.getFieldsValue();
    _.map(payload, (value, key) => {
      if (value === '') {
        payload[key] = undefined;
      }
    });

    dispatch && dispatch({
      type: 'global/getModel',
      payload: {table}
    });

    dispatch && dispatch({
      type: 'vendor/findMany',
      payload: {}
    });
    payload.isRent = false;
    dispatch && dispatch({
      type: 'procure/findStatistic',
      payload
    });
    dispatch && dispatch({
      type: 'procure/findMany',
      payload
    });
  }

  onDelete = record => {
    const {code} = record;
    this.props.dispatch({
      type: 'procure/deleteOne',
      payload: {code, tenantCode: this.getTenantCode()}
    })
      .then(res => {
        this.requestReturn(res);
        this.componentDidMount();
      });
  };

  onCreateOrEdit = async (values) => {
    let _title = values ? `编辑${title}` : `新建${title}`;
    ModalView.open(ModalCreateOrEditProcureOrder, {
      title: _title,
      width: '1580px',
      maskClosable: false
    }, {
      values,
      refresh: () => {
        console.log('refresh');
        this.componentDidMount();
      },
      callback: (data) => {
        data.isRent = false;
        if (values) {
          this.props.dispatch({
            type: 'procure/updateOne',
            payload: data
          }).then(res => {
            this.requestReturn(res);
            this.componentDidMount();
          });
          return;
        }
        data.code = "PRO" + Date.now().valueOf();
        this.props.dispatch({
          type: 'procure/create',
          payload: data
        }).then(res => {
          this.requestReturn(res);
          this.componentDidMount();
        });
      }
    });
  };
  onCopy = async (material) => {
    const {dispatch, orders} = this.props;
    let _title = "复制";
    let values = material ? material : {};
    const res = await dispatch({
      type: 'global/getCode',
      payload: {prefix: 'PRO'}
    });

    const {code} = material;
    values = _.find(orders.array, item => {
      return item.code === code;
    });

    values.code = res.code;
    ModalView.open(ModalCreateOrEditProcureOrder, {
      title: _title,
      width: '920px'
    }, {
      values,
      codePrefix: 'PRO',
      dispatch: dispatch,
      table,
      title: _title,
      disabledProps: ['code'],
      callback: (data) => {
        data.createUser = this.getLoginUser();
        data.createUsername = this.getLoginUsername();
        data.tenantCode = this.getTenantCode();
        data.table = table;
        delete data["_id"];
        delete data['reviewStatus'];
        this.props.dispatch({
          type: 'procure/create',
          payload: data
        }).then(res => {
          this.componentDidMount();
        });
      }
    });
  };

  invoice = record => {
    const {code, invoice} = record;
    const temp = invoice === '未收票' ? "已收票" : "未收票";
    const invoiceDate = invoice === '未收票' ? moment().format('YYYY-MM-DD') : "";

    this.props.dispatch({
      type: 'procure/updateOne',
      payload: {code, invoice: temp, invoiceDate}
    }).then(res => {
      this.requestReturn(res);
      this.componentDidMount();
    });
  };
  menu = record => {
    // const {invoice} = record;
    // const temp = invoice === '未收票' ? "收票" : "取消收票";
    return (
      <Menu>
        <Menu.Item disabled={record.reviewStatus === '同意'}>
          <a style={{marginRight: '6px'}} disabled={record.reviewStatus === '同意'}
             onClick={() => this.onCreateOrEdit(record)}>编辑</a>
        </Menu.Item>
        <Menu.Item>
          <a style={{marginRight: '6px'}}
             onClick={() => this.onCopy(record)}>复制</a>
        </Menu.Item>
        {/*<Menu.Item>*/}
        {/*  <a onClick={() => this.invoice(record)}>*/}
        {/*    {temp}*/}
        {/*  </a>*/}
        {/*</Menu.Item>*/}
      </Menu>);
  };

  getSearchFields = () => {
    return [
      <FormField
        label="编码"
        name="code"
        key={1}
      >
        <Input allowClear placeholder={`请输入${title}编码`}/>
      </FormField>,
      <FormField
        label="供应商"
        name="vendor"
        key={2}
      >
        <Input allowClear placeholder="请输入供应商"/>
      </FormField>,
      <FormField
        label="材料类型"
        name="materialType"
        key={6}
      >
        <Select allowClear placeholder="请选择">
          <Option value={'主材'}>{'主材'}</Option>
          <Option value={'辅材'}>{'辅材'}</Option>
        </Select>
      </FormField>,
      <FormField
        label="创建时间"
        name="createdTs"
        key={3}
        initialValue={[this.getSearchStart1Months(), this.getDefaultSearchEndDate()]}
      >
        <RangePicker allowClear={true}
          // style={{ width: '150%' }}
        />
      </FormField>,
      <FormField
        label="审核状态"
        name="reviewStatus"
        key={4}
      >
        <Select allowClear placeholder="请选择">
          <Option value={'待审核'}>{'待审核'}</Option>
          <Option value={'同意'}>{'同意'}</Option>
          <Option value={'驳回'}>{'驳回'}</Option>
        </Select>
      </FormField>,
          <FormField
            label="验收状态"
            name="acceptanceStatus"
            key={5}
          >
            <Select allowClear placeholder="请选择">
              <Option value={'待验收'}>{'待验收'}</Option>
              <Option value={'验收通过'}>{'验收通过'}</Option>
              <Option value={'驳回'}>{'驳回'}</Option>
            </Select>
          </FormField>
    ];
  };
  export = () => {
    const data = this.props.form.getFieldsValue();
    let {supplier, code, plannedDeliveryDate, reviewStatus, createdTs} = data;

    const start = createdTs && createdTs.length === 2 ? createdTs[0] : undefined;
    const end = createdTs && createdTs.length === 2 ? createdTs[1] : undefined;
    if (reviewStatus) {
      reviewStatus = reviewStatus === 0 ? undefined : reviewStatus;
      reviewStatus = reviewStatus === 1 ? '待审核' : reviewStatus;
      reviewStatus = reviewStatus === 2 ? '同意' : reviewStatus;
      reviewStatus = reviewStatus === 3 ? '驳回' : reviewStatus;
    }
    /**
     * 输入框清除之后会成为 ”“
     * @type {undefined}
     */
    supplier = supplier === '' ? undefined : supplier;
    code = code === '' ? undefined : code;
    plannedDeliveryDate = plannedDeliveryDate === '' || plannedDeliveryDate === null || plannedDeliveryDate === undefined ?
      undefined : moment(plannedDeliveryDate).format('YYYY-MM-DD');
    this.props.dispatch({
      type: 'procure/exportExcel',
      payload: {supplier, code, plannedDeliveryDate, reviewStatus, start, end}
    }).then(res => {
      if (res) {
        const {result = {}} = res;
        const {header, data} = result;
        exportExcel(header, data, '采购单');
      }
    });
  };

  render() {
    const {statistic = {}, _notify, orders = [], form} = this.props;
    const {showDetail, record = {}, current = 1, loading, total = 0} = this.state;

    if (_notify) {
      notify(_notify);
    }
    const {amount = 0, count = 0} = statistic;
    const model = this.props['ProcureOrderModel'];
    const cols = [];

    cols.push(...this.getTableColumns(model));
    cols.push({
      title: '操作', dataIndex: 'operation', key: 'operation',
      width: 160, fixed: 'right',
      render: (value, record) => {
        return (
          <span>
            {<a style={{marginRight: '6px'}}
                onClick={() => this.setState({showDetail: true, record})}>详情</a>}
            {
              <Popconfirm
                title="确认删除"
                onConfirm={() => this.onDelete(record)}
                okText="是"
                cancelText="否"
              >
                <a style={{marginRight: '6px'}} disabled={record.reviewStatus === '同意'}>删除</a>
              </Popconfirm>
            }
            <Dropdown overlay={this.menu(record)}>
              <a className="ant-dropdown-link">
                更多  <Icon type="down"/>
              </a>
            </Dropdown>
            </span>
        );
      }
    });
    return (
      <Form className={styles.content}>
        <ViewTitle
          title={`${title}列表`}
          level={1}
          actions={[
            // <Button onClick={() => this.export()}>导出</Button>,
            <Button type="primary" onClick={() => this.onCreateOrEdit(undefined)}>添加</Button>]}></ViewTitle>
        <SearchForm
          style={{marginLeft: '6px', marginRight: '6px'}}
          onSearch={() => {
            this.state.current = 1;
            this.componentDidMount();
          }}
          onReset={this.handleReset}
          cols={3}
          min={6}
          expandText="展开"
          form={form}
        >
          {this.getSearchFields()}
        </SearchForm>
        <div style={{background: '#ECECEC', padding: '30px'}}>
          <Row gutter={16}>
            <Col span={12}>
              <Card>
                <Statistic
                  title="采购物料总数量"
                  value={count}
                  precision={2}
                  valueStyle={{color: '#3f8600'}}
                  suffix="KG"
                />
              </Card>
            </Col>
            <Col span={12}>
              <Card>
                <Statistic
                  title="采购物料总金额"
                  value={amount}
                  precision={2}
                  valueStyle={{color: '#cf1322'}}
                  suffix="元"
                />
              </Card>
            </Col>
          </Row>
        </div>
        <Table
          loading={loading}
          className={styles.antTable}
          bordered={true}
          columns={cols}
          dataSource={orders}
          scroll={{x: true}}
          pagination={{
            current: this.state.current,
            total: this.state.total,
            showSizeChanger: true,
            onChange: page => {
              this.state.current = page;
              this.componentDidMount();
            },
            onShowSizeChange: (current, pageSize) => {
              this.state.current = 1;
              this.state.pageSize = pageSize;
              this.componentDidMount();
            }
          }}
          // pagination={{pageSize: 100}}
          //scroll={{ x: 1300 }}
        ></Table>

        {showDetail && <Drawer
          visible={showDetail}
          title={`${title}详情`}
          placement="left"
          width={'80%'}
          style={{padding: 0}}
          onClose={() => {
            this.setState({showDetail: false});
          }}
        >
          <ModalProcureOrderDetail
            values={record}
          > </ModalProcureOrderDetail>
        </Drawer>}
      </Form>
    );
  }
}
